import React, { useState, useCallback, useEffect } from 'react'
import { SimpleSelector } from './simpleSelector'
import { NotifyType } from '../../common/enums'
import { notify } from '../../source/notify'
import { getAllElementsOfPage } from '../../source/getData'
import { withSignal } from '../../common/withSignal';

export const ElementSelector = ({ page, elementSelectorId, onSelectItem, readOnly }) => {
  const [dataSource, setDataSource] = useState([])
  const filterDataSource = useCallback(value => item => item.selector.includes(value) || item.remark.includes(value), [])
  const getItemValue = useCallback(item => item.id, [])
  const renderItem = useCallback(item => `${item.selector}[${item.remark}]`, [])

  useEffect(() => {
    return withSignal(signal => {
      getAllElementsOfPage(page, { signal })
        .then(data => setDataSource(data))
        .catch(err => notify(NotifyType.error, err))
    })
  }, [page])

  return <SimpleSelector dataSource={dataSource} filterDataSource={filterDataSource}
    getItemValue={getItemValue} initValue={elementSelectorId} onSelectItem={onSelectItem}
    readOnly={readOnly} renderItem={renderItem} />
}